package com.markul.android.ui.location

import android.media.ExifInterface
import android.util.Log
import com.baidu.mapapi.model.LatLng
import com.markul.android.logic.room.AlbumInfo
import java.lang.Exception
import java.lang.IllegalArgumentException

class GetAlbumLocation {

    fun getPhotoLocation(imagePath: String):LatLng{
        val albumInfo:AlbumInfo=getPhotoInfo(imagePath)
        val latLng=LatLng(albumInfo.lat,albumInfo.lng)
        return latLng
    }

    fun getPhotoInfo(imagePath: String): AlbumInfo {
        var output1:Double=0.0
        var output2:Double=0.0
        var datetime:String?=""
        try {
            val exifInterface = ExifInterface(imagePath)
            datetime= exifInterface.getAttribute(ExifInterface.TAG_DATETIME)// 拍摄时间
            val latValue: String? = exifInterface.getAttribute(ExifInterface.TAG_GPS_LATITUDE)
            val lngValue: String? = exifInterface.getAttribute(ExifInterface.TAG_GPS_LONGITUDE)
            val latRef: String? = exifInterface.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF)
            val lngRef: String? = exifInterface.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF)
            Log.i("TAG", "$latValue;$lngValue;$latRef;$lngRef")
            Log.i("TAG", "$datetime")
            if (latValue != null && latRef != null && lngValue != null && lngRef != null) {
                try {
                    output1 = convertRationalLatLonToFloat(latValue, latRef)
                    output2 = convertRationalLatLonToFloat(lngValue, lngRef)
                } catch (e: IllegalArgumentException) {
                    e.printStackTrace()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        val albumInfo= AlbumInfo(output1,output2,datetime)
        return albumInfo
    }

    private fun convertRationalLatLonToFloat(
        rationalString: String, ref: String
    ): Double{
        val parts = rationalString.split(",".toRegex()).toTypedArray()
        var pair: Array<String> = parts[0].split("/".toRegex()).toTypedArray()
        val degrees = pair[0].trim { it <= ' ' }.toDouble() / pair[1].trim { it <= ' ' }
            .toDouble()
        pair = parts[1].split("/".toRegex()).toTypedArray()
        val minutes = pair[0].trim { it <= ' ' }.toDouble() / pair[1].trim { it <= ' ' }
            .toDouble()
        pair = parts[2].split("/".toRegex()).toTypedArray()
        val seconds = pair[0].trim { it <= ' ' }.toDouble() / pair[1].trim { it <= ' ' }
            .toDouble()
        val result = degrees + minutes / 60.0 + seconds / 3600.0
        return if (ref == "S" || ref == "W") {
            (-result)
        } else result
    }
}